import { RESOLVER_NAME, treeReduce } from '../components/FormulaEditor'

/**
 * 转换成FormulaEditor可以识别的公式
 * 注：要公式正确的时候才能转换正确
 * @example convert2EditorFormula("(;1;(;2;););FXJ2G;") => "(;1;(;2;););@FXJ2G#"
 * @param funcString
 * @returns {string}
 */
const convert2EditorFormula = (funcString = '') => {
    // 如果给的公式，最后没有分号，补上分号
    const fixFunString = funcString + (!funcString || funcString.endsWith(';') ? '' : ';');

    return fixFunString.replace(/([^;]+);/gi, (match, group1) => {
        // 如果是数字
        if (/^[+-]?\d+\.?\d*$/.test(group1)) {
            return group1;
        }

        // 兼容后台1;.;5;的情况
        if (/^\.$/.test(group1)) {
            return group1;
        }

        // 如果是操作符
        if (/^[+\-*/()]$/g.test(group1)) {
            return group1;
        }
        return `@${group1}$`;
    });
}


/**
 * 将FormulaEditor的树结构转成后台可以识别的公式
 * @param formulaTree
 * @returns {string|*}
 */
const convert2ServerFormula = formulaTree => {
    if (!formulaTree?.length) {
        return '';
    }

    const { serverFormula: result } = treeReduce(
        formulaTree,
        ({ serverFormula }, node, afterTrigger) => {
            if (node.name === RESOLVER_NAME.NUMBER || node.name === RESOLVER_NAME.OPERATOR) {
                return { serverFormula: `${serverFormula}${node.value};` };
            }

            if (node.name === RESOLVER_NAME.CONDITION) {
                return { serverFormula: `${serverFormula}${node.value.replace('@', '').replace('$', '')};` };
            }

            if (node.name === RESOLVER_NAME.GROUP) {
                return { serverFormula: `${serverFormula}${!afterTrigger ? '(' : ')'};` };
            }

            if (node.name === RESOLVER_NAME.ERROR && !afterTrigger) {
                return { serverFormula: `${serverFormula}${node.value};` };
            }

            return { serverFormula };
        },
        { serverFormula: '' }
    );

    // 去除最后的分号
    return result.replace(/;$/, '');
};

export { convert2EditorFormula, convert2ServerFormula };
